package com.wowangz.cms.systemmanage.duty.api;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.dailyoperation.services.pojo.Menu;
import com.wowangz.cms.dailyoperation.services.service.MenuService;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.duty.pojo.Duty;
import com.wowangz.cms.systemmanage.duty.pojo.DutyMenu;
import com.wowangz.cms.systemmanage.duty.service.DutyMenuService;
import com.wowangz.cms.systemmanage.duty.service.DutyService;

@Scope("prototype")
@Controller
public class DutyController extends BaseController {
	
	/**
	 * 打开职责设置页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/systemmanage/dutymanage/dutyset/toDutyList.web", method = RequestMethod.GET)
	public String toDutyList(HttpServletRequest request,HttpServletResponse response, Model model){
		
		return "/WEB-INF/jsp/systemmanage/dutymanage/dutyset/dutyList";		
	}
	
	/**
	 * 打开职业列表加载列表数据
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/systemmamage/dutymanage/dutyset/queryDutyListInfoDataGrid.json")
	public void querySparticipantbankListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		DutyService dutyService = (DutyService) IssTransactionContainer.getInstance(DutyService.class, false);
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;

		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);

			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			
			long resultCount = dutyService.findResultCount(map);
			List<Duty> resultList = dutyService.findResultList(map);

			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);

			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("dutycode", DataTypeConstant.STRING);
			dataStyle.addDepict("dutyname", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("checkstatus", SysConstant.CheckStatus.class, "getName", new Class[] { long.class });
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);

			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转到新增页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/systemmamage/dutymanage/dutyset/toAddDuty.web", method = RequestMethod.GET)
	public String toAddDuty(HttpServletRequest request,HttpServletResponse response, Model model){
		
		return "/WEB-INF/jsp/systemmanage/dutymanage/dutyset/dutyAdd";		
	}
	
	/**
	 * 获取菜单
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @param writer
	 * @throws ControllerException
	 */
	@RequestMapping(value="/systemmamage/dutymanage/dutyset/queryMenuDirectoryTree.json", method=RequestMethod.POST)
	public void queryMenuDirectoryTree(HttpServletRequest request, HttpServletResponse response, Model model){
		MenuService menuService = (MenuService) IssTransactionContainer.getInstance(MenuService.class, false);
		String menucode = request.getParameter("menucode");
		int menulevel = 1;
		if(request.getParameter("menulevel") != null){
			menulevel = Integer.parseInt(request.getParameter("menulevel"));
			menulevel += 1;
		}
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		hashMap.put("statusid", SysConstant.RecordStatus.VALID);
		List<Menu> list = menuService.queryMenuAll(hashMap);
		
		StringBuffer json = new StringBuffer("[");
		json = forlist(json,list,menulevel,menucode);
		
		try {
			response.getWriter().write(json.substring(0,json.length()-1)+"]");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 遍历菜单数据，并拼接成json字符串
	 * @param json  json字符串
	 * @param list  缓存获取的商户有的菜单
	 * @param hashmap 缓存获取所有的菜单
	 * @param menulevel 节点层级 
	 * @param zi_menucode 
	 * @return
	 */
	public StringBuffer forlist(StringBuffer json,List<Menu> list,int menulevel,String zi_menucode){
		
		for (Menu storeMenu : list)
		{
			long menuid = storeMenu.getId();
			String menucode = storeMenu.getMenucode();
			String menuname = storeMenu.getMenuname();
			int menulevel_int = storeMenu.getMenulevel();
			
			if(menulevel_int == menulevel ){
				// 如果1级以上的菜单menucode包含1级某个父菜单的menucode，那么该节点某个父菜单的子节点
				// 比如，父菜单"账号管理"的menucode
				// 是MO1,在2级菜单中，如果某个菜单“申请账号”的menucode是MO1-100，
				// 那么 申请账号 是账号管理的 子菜单
				if(zi_menucode == null){
					json.append("{menucode:'").append(menucode).append("'")
					.append(",menuid:'").append(menuid).append("'")
					.append(",name:'").append(menuname).append("'")
					.append(",menulevel:'").append(menulevel_int).append("'")
					.append(",isParent:true")
					.append("}").append(",");
				}
				else if (menucode.contains(zi_menucode)) {
					json.append("{menucode:'").append(menucode).append("'")
						.append(",menuid:'").append(menuid).append("'")
						.append(",name:'").append(menuname).append("'")
						.append(",menulevel:'").append(menulevel_int).append("'")
						.append(",isParent:").append(isParent(menulevel,zi_menucode,list) == true ? "true":"false")
						.append("}").append(",");
				}
			}
		}
		return json;
	}
	
	/**
	 * 判断是否父节点
	 * @param menulevel 菜单层级
	 * @param zi_menucode 菜单编码
	 * @param list  缓存获取的商户有的菜单
	 * @param hashmap 缓存获取所有的菜单
	 * @return
	 */
	public boolean isParent(int menulevel,String zi_menucode,List<Menu> list){
		int nums = menulevel + 1;
		int sum = 0;
		for (Menu storeMenu : list){
			//判断该节点在list中是否有子节点的依据： 下一级节点 和 下一级节点Menucode是否包含父类Menucode
			int zi_menulevel = storeMenu.getMenulevel();
			String menucode = storeMenu.getMenucode();
			if(nums == zi_menulevel && menucode.contains(zi_menucode)){
				sum++;
				if(sum == 2){
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 验证
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmamage/dutymanage/dutyset/validattionDuty.json", method = RequestMethod.POST)
	public void validattionDuty(HttpServletRequest request,HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		DutyService dutyService = (DutyService) IssTransactionContainer.getInstance(DutyService.class, false);
		try {
			Duty duty = null;
			StringBuffer errorMsg = new StringBuffer();
			HashMap<String, Object> map = new HashMap<String, Object>();
			duty = (Duty) ServletUtils.getParametersToBaseEntity(request, Duty.class);
			
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(null != duty.getId()){
				map.put("id", duty.getId());
			}
			map.put("dutycode", duty.getDutycode());
			if(!dutyService.validationDuty(map)){
				errorMsg.append(MessageResourcesUtils.getMessage(request, "systemmamage.dutymanage.dutyset.dutyAdd.alert1"));
			}
			map.remove("dutycode");
			
			if(StringUtils.isNotEmpty(errorMsg.toString())){
				userContext.setErrorMessage(errorMsg.toString());
			}
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 新增
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/systemmamage/dutymanage/dutyset/addDuty.web", method=RequestMethod.POST)
	public String addDuty(HttpServletRequest request, Model model){
		DutyService dutyService = (DutyService) IssTransactionContainer.getInstance(DutyService.class, false);
		DutyMenuService dutyMenuService = (DutyMenuService)IssTransactionContainer.getInstance(DutyMenuService.class, false);
		Duty duty = null;
		DutyMenu dutyMenu = new DutyMenu();
		try{
			//新增职责
			duty = (Duty)ServletUtils.getParametersToBaseEntity(request,Duty.class);
			duty.setCheckstatus(String.valueOf(SysConstant.CheckStatus.SAVE));
			duty.setInputtime(new Date());
			duty.setInputuserid(userContext.getLoginUser().getId());
			duty.setModifytime(new Date());
			duty.setModifyuserid(userContext.getLoginUser().getId());
			duty.setStatusid(SysConstant.RecordStatus.VALID);
			dutyService.add(duty);
			
			//新增职责和菜单
			String menuids = request.getParameter("menuids");
			String[] menuid = menuids.split(",");
			for(int i =0;i<menuid.length;i++){
				dutyMenu.setDutyid(duty.getId());
				dutyMenu.setMenuid(Long.parseLong(menuid[i].toString()));
				dutyMenuService.add(dutyMenu);
			}
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		return "/WEB-INF/jsp/systemmanage/dutymanage/dutyset/dutyAdd";
	}
	
	/**
	 * 跳转修改页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmamage/dutymanage/dutyset/toUpdateDuty.web", method = RequestMethod.GET)
	public String toUpdateDuty(HttpServletRequest request, Model model) {
		DutyService dutyService = (DutyService) IssTransactionContainer.getInstance(DutyService.class, false);
		DutyMenuService dutyMenuService = (DutyMenuService) IssTransactionContainer.getInstance(DutyMenuService.class, false);
		
		String id = request.getParameter("id");
		String menu_ids = "";
		Duty duty = null;
		List<DutyMenu> dutyMenulist = null;
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		hashMap.put("id", id);
		hashMap.put("statusid", SysConstant.RecordStatus.VALID);
		try {
			duty = dutyService.findDutyById(hashMap);
			dutyMenulist = dutyMenuService.findDutyAgencyById(hashMap);
			for(int i =0;i<dutyMenulist.size();i++){
				//将菜单ID拼接字符串
				if("".equals(menu_ids)){
					menu_ids = String.valueOf(dutyMenulist.get(i).getMenuid());
				}else{
					menu_ids = menu_ids +","+String.valueOf(dutyMenulist.get(i).getMenuid());
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		model.addAttribute("duty",duty);
		model.addAttribute("menu_ids",menu_ids);
		
		return "/WEB-INF/jsp/systemmanage/dutymanage/dutyset/dutyUpdate";
	}
	
	/**
	 * 修改
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmamage/dutymanage/dutyset/updateDuty.web", method = RequestMethod.POST)
	public String updateDuty(HttpServletRequest request, Model model) {
		DutyService dutyService = (DutyService) IssTransactionContainer.getInstance(DutyService.class, false);
		DutyMenuService dutyMenuService = (DutyMenuService) IssTransactionContainer.getInstance(DutyMenuService.class, false);
		
		Duty duty = null;
		DutyMenu dutyMenu = new DutyMenu();
		try{
			//修改职责
			duty = (Duty)ServletUtils.getParametersToBaseEntity(request,Duty.class);
			duty.setCheckstatus(String.valueOf(SysConstant.CheckStatus.SAVE));
			duty.setModifytime(new Date());
			duty.setModifyuserid(userContext.getLoginUser().getId());
			dutyService.update(duty);
			
			dutyMenu.setDutyid(duty.getId());
			dutyMenuService.delete(dutyMenu);
			
			//新增职责和菜单
			String menuids = request.getParameter("menu_ids");
			String[] menuid = menuids.split(",");
			for(int i =0;i<menuid.length;i++){
				dutyMenu.setDutyid(duty.getId());
				dutyMenu.setMenuid(Long.parseLong(menuid[i].toString()));
				dutyMenuService.add(dutyMenu);
			}
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert1"));
			userContext.setCloseWindow(true);
		}catch(Exception ex){
			ex.printStackTrace();
		}
		
		return "/WEB-INF/jsp/systemmanage/dutymanage/dutyset/dutyUpdate";
	}
	
	/**
	 * 删除
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemmamage/dutymanage/dutyset/deleteDuty.json", method = { RequestMethod.GET, RequestMethod.POST })
	public void deleteDuty(HttpServletRequest request, HttpServletResponse response, Model model) {
		DutyService dutyService = (DutyService) IssTransactionContainer.getInstance(DutyService.class, false);
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			Long id = Long.valueOf(getRequest().getParameter("id"));
			
			Duty duty = new Duty();
			duty.setId(id);
			duty.setStatusid(SysConstant.RecordStatus.INVALID);
			dutyService.update(duty);
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "alertinfo.common.java.alert3"));

			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 跳转明细页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemmamage/dutymanage/dutyset/toViewDuty.web", method = RequestMethod.GET)
	public String toViewDuty(HttpServletRequest request, Model model) {
		MenuService menuService = (MenuService) IssTransactionContainer.getInstance(MenuService.class, false);
		DutyService dutyService = (DutyService) IssTransactionContainer.getInstance(DutyService.class, false);
		DutyMenuService dutyMenuService = (DutyMenuService) IssTransactionContainer.getInstance(DutyMenuService.class, false);
		
		String id = request.getParameter("id");
		String menu_ids = "";
		Duty duty = null;
		List<DutyMenu> dutyMenulist = null;
		HashMap<String,Object> hashMap = new HashMap<String, Object>();
		hashMap.put("id", id);
		hashMap.put("statusid", SysConstant.RecordStatus.VALID);
		try {
			duty = dutyService.findDutyById(hashMap);
			//拼接菜单ID字符串
			dutyMenulist = dutyMenuService.findDutyAgencyById(hashMap);
			for(int i =0;i<dutyMenulist.size();i++){
				if("".equals(menu_ids)){
					menu_ids = String.valueOf(dutyMenulist.get(i).getMenuid());
				}else{
					menu_ids = menu_ids +","+String.valueOf(dutyMenulist.get(i).getMenuid());
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		String menuid_all = "";
		HashMap<String,Object> hashMaps = new HashMap<String, Object>();
		hashMaps.put("statusid", SysConstant.RecordStatus.VALID);
		List<Menu> list = menuService.queryMenuAll(hashMaps);
		for(Menu menu : list){
			if("".equals(menuid_all)){
				menuid_all = menuid_all+menu.getId();
			}else{
				menuid_all = menuid_all+","+menu.getId();
			}
		}
		
		model.addAttribute("duty",duty);
		model.addAttribute("menu_ids",menu_ids);
		model.addAttribute("menuid_all",menuid_all);
		
		return "/WEB-INF/jsp/systemmanage/dutymanage/dutyset/dutyView";
	}
}
